package com.hyt.it.ogt.kq.main.controller.gov;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hyt.common.apiInfor.ApiResponse;
import com.hyt.core.util.FastJsonUtil;
import com.hyt.exception.annotation.ThrowsAdvice;
import com.hyt.it.ogt.kq.common.config.exception.KqException;
import com.hyt.it.ogt.kq.common.enums.UserBusinessAccessTypeEnum;
import com.hyt.it.ogt.kq.common.gov.annotation.NoRepeatCommit;
import com.hyt.it.ogt.kq.common.gov.config.swagger.ApiVersionConstant;
import com.hyt.it.ogt.kq.common.gov.constant.ResponseCode;
import com.hyt.it.ogt.kq.service.admission.IAdmissionTicketInfoService;
import com.hyt.it.ogt.kq.service.gov.model.param.CopyTaskParam;
import com.hyt.it.ogt.kq.service.gov.model.param.TaskInfoParam;
import com.hyt.it.ogt.kq.service.gov.model.param.TaskPageParam;
import com.hyt.it.ogt.kq.service.gov.model.param.TaskPublishParam;
import com.hyt.it.ogt.kq.service.gov.model.vo.TestClassifyVO;
import com.hyt.it.ogt.kq.service.gov.model.vo.task.TaskPageVO;
import com.hyt.it.ogt.kq.service.gov.service.ITaskService;
import com.hyt.loginfo.controller.BaseLoginController;
import com.hyt.loginfo.model.User;
import com.hyt.loginfo.service.IUaBusinessAccessService;
import com.hyt.loginfo.util.UserIdToNameUtil;
import com.hyt.swagger.ApiVersion;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperationSort;
import io.swagger.annotations.ApiSort;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * <p>
 * 考试任务表 前端控制器
 * </p>
 *
 * @author huangyh
 * @since 2021-03-08
 */
@RestController
@Api(tags = "101.考试任务接口", value = "考试任务接口")
@ApiSort(value = 101)
@RequestMapping("/kw/gov/task")
@Slf4j
public class TaskController extends BaseLoginController {

    @Autowired
    private ITaskService iTaskService;

    @Autowired
    protected UserIdToNameUtil<TaskPageVO> userIdToNameUtil;
    @Resource
    private IAdmissionTicketInfoService iAdmissionTicketInfoService;
    @Resource
    private IUaBusinessAccessService iUaBusinessAccessService;

    @ApiOperation(
            value = "1.1 新增或编辑任务",
            notes = "30000:新增和编辑任务参数成功; "
    )
    @ApiOperationSort(value = 1)
    @ApiVersion(group = ApiVersionConstant.V2_4_10)
    @PostMapping("/addOrUpdateTaskConfig")
    @ThrowsAdvice(code = 43010101, print = "新增和编辑任务数据异常")
    @NoRepeatCommit(lockName = "no-repeat-save-or-update-task-lock")
    public ApiResponse<Object> addOrUpdateTaskConfig(@Valid @RequestBody TaskInfoParam taskInfoParam) {
        if (log.isDebugEnabled()) {
            log.debug("# [新增和编辑任务]参数参数 ： {}", JSON.toJSONString(taskInfoParam));
        }
        try {
            User loginUser = getSysUser();
            log.info("获取到的用户信息：{}", FastJsonUtil.getBeanToJson(loginUser));
            log.info("getOfficeId : {}", getOfficeId());
            log.info("getDeptId : {}", getDeptId());
            
            taskInfoParam.setUser(loginUser);
            String taskId = iTaskService.addOrUpdateTaskConfig(taskInfoParam);

            // 更新考试名称和时间
            try {
                iAdmissionTicketInfoService.updateKwExam(taskId, loginUser);
            } catch (Exception e) {
                log.error("[考务][新增和编辑任务][更新准考证信息]更新考试名称和时间异常，taskId：{}",taskId, e);
            }
            return ApiResponse.builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .data(taskId)
                    .build();
        } catch (KqException k) {
            log.error("# 新增和编辑任务参数异常: {}", k.getErrMsg());
            if (ResponseCode.VALID_ONLINE_TASK_CONFIG_ERROR.getCode() == k.getErrCode()) {
                return ApiResponse.builder().code(k.getErrCode()).data(k.getData()).build();
            } else {
                return ApiResponse.builder().code(k.getErrCode()).data(k.getErrMsg()).build();
            }
        } catch (Exception e) {
            log.error("# 新增和编辑任务参数异常:", e);
            return ApiResponse.builder().code(ResponseCode.TASK_ADD_EXCEPTION.getCode()).build();
        }
    }

    @ApiOperation(
            value = "1.2 获取任务信息",
            notes = "30000:获取任务信息成功; "
    )
    @ApiOperationSort(value = 2)
    @ApiVersion(group = ApiVersionConstant.V2_4_10)
    @ThrowsAdvice(code = 43010201, print = "获取任务信息异常")
    @GetMapping("/getTaskInfoParam")
    public ApiResponse<TaskInfoParam> getTaskInfoParam(@RequestParam(required = false) String taskId) {
        log.info("# [获取任务信息]参数 ： {}", taskId);
        return ApiResponse.<TaskInfoParam>builder()
                .code(ResponseCode.SUCCESS.getCode())
                .data(iTaskService.getTaskInfoParam(taskId, getOfficeId()))
                .build();
    }

    /**
     * 查询考试任务分页数据
     *
     * @param pageParam 分页参数
     * @return ApiResponse
     */
    @ApiOperation(
            value = "1.3 查询考试任务分页数据",
            notes = "20000:成功;30008:查询试题分页数据异常"
    )
    @ApiOperationSort(value = 3)
    @ApiVersion(group = ApiVersionConstant.V2_4_10)
    @ThrowsAdvice(code = 43010301, print = "查询考试任务分页数据异常")
    @GetMapping(value = "/page")
    public ApiResponse<Page<TaskPageVO>> page(TaskPageParam pageParam) {
        log.info("# [查询考试任务分页数据]参数 ： {}", pageParam.toString());
        User loginUser = getSysUser();
        log.info("获取到的用户信息：{}", FastJsonUtil.getBeanToJson(loginUser));
        log.info("getOfficeId : {}", getOfficeId());
        log.info("getDeptId : {}", getDeptId());
        log.info("getDeptIds : {}", getDeptIds());
        Page<TaskPageVO> taskPage = iTaskService.page(pageParam, getOfficeId(), getDeptIds());
        return ApiResponse.<Page<TaskPageVO>>builder()
                .code(ResponseCode.SUCCESS.getCode())
                .data(taskPage)
                .build();
    }

    @ApiOperation(
            value = "1.4 修改任务发布状态",
            notes = "30000:修改任务发布状态成功; 30013:任务下还没有编排考生，不允许发布; 30026:任务发布状态不存在; 30027:任务发布参数校验错误"
    )
    @ApiOperationSort(value = 4)
    @PutMapping("/query/updateTaskPublishStatus")
    public ApiResponse<Object> updateTaskPublishStatus(@RequestBody @Valid TaskPublishParam taskPublishParam) {
        try {
            iTaskService.updateTaskPublishStatus(taskPublishParam);
            return ApiResponse.builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .build();
        } catch (KqException k) {
            log.error("# 修改任务发布状态业务异常: {}", k.getErrMsg());
            return ApiResponse.builder()
                    .code(k.getErrCode())
                    .build();
        } catch (Exception e) {
            log.error("# 修改任务发布状态异常:", e);
            return ApiResponse.builder()
                    .code(ResponseCode.TASK_STATE_UPDATE_FAIL.getCode())
                    .build();
        }
    }

    @ApiOperation(
            value = "1.5 复制任务",
            notes = "30000:复制任务成功; "
    )
    @ApiVersion(group = ApiVersionConstant.V2_4_10)
    @ApiOperationSort(value = 5)
    @ThrowsAdvice(code = 43010501, print = "复制任务异常")
    @PostMapping("/copyTask")
    public ApiResponse<Object> copyTask(@Valid @RequestBody CopyTaskParam copyTaskParam) {
        log.debug("# 复制任务参数: {}", FastJsonUtil.getBeanToJson(copyTaskParam));
        iTaskService.copyTask(copyTaskParam);
        return ApiResponse.builder()
                .code(ResponseCode.SUCCESS.getCode())
                .build();
    }

    @ApiOperation(
            value = "1.6 获取考试分类",
            notes = "30000:获取考试分类成功; "
    )
    @ApiOperationSort(value = 6)
    @ThrowsAdvice(code = 43010601, print = "获取考试分类异常")
    @PostMapping("/getTestClassify")
    public ApiResponse<List<TestClassifyVO>> getTestClassify() {
        return ApiResponse.<List<TestClassifyVO>>builder()
                .code(ResponseCode.SUCCESS.getCode())
                .data(iTaskService.getTestClassify())
                .build();
    }

    @ApiOperation(
            value = "1.7 删除考务任务"
    )
    @ApiOperationSort(value = 7)
    @ApiVersion(group = ApiVersionConstant.V2_4_10)
    @ThrowsAdvice(code = 43010701, print = "删除考务任务失败")
    @GetMapping("/deleteTask")
    public ApiResponse<Boolean> deleteTask(@RequestParam String taskId) {
        return ApiResponse.<Boolean>builder()
                .code(ResponseCode.SUCCESS.getCode())
                .data(iTaskService.deleteTask(taskId))
                .build();

    }

    @ApiOperation(
            value = "1.8 获取当前用户菜单权限"
    )
    @ApiOperationSort(value = 8)
    @GetMapping("/getUserMenuPermission")
    public ApiResponse<Integer> getUserMenuPermission(@RequestParam String taskId) {
        int permission = 0; // 显示全部
        List<String> taskIdList = iUaBusinessAccessService.getBusinessPermissionById(getUserId(), UserBusinessAccessTypeEnum.KW_TASK_PERMISSION.getCode());
        if(CollectionUtils.isNotEmpty(taskIdList)) {
            if(taskIdList.stream().filter(i -> i.equalsIgnoreCase(taskId)).findFirst().isPresent()) {
                permission = 1; // 显示4个菜单
            }
        }
        return ApiResponse.<Integer>builder()
                .code(ResponseCode.SUCCESS.getCode())
                .data(permission)
                .build();
    }

}
